#include "StdAfx.h"
#include "MemoryMag.h"

#include "LogWrapper.h"

CMemoryMag::CMemoryMag(void)
{
	m_hModule				= NULL;
	m_lpCreateMemoryPool	= NULL;
	m_lpDestroyMemoryPool	= NULL;
}

CMemoryMag::~CMemoryMag(void)
{
	this->Destroy();
}

bool CMemoryMag::Initialize()
{
#ifdef _WIN64
	m_hModule = LoadLibrary(L"CTMemoryPool64.dll");
#else
	m_hModule = LoadLibrary(L"CTMemoryPool.dll");
#endif
	DWORD dwError = GetLastError();
	if (!m_hModule)
	{
		CSingleton<CLogWrapper>::Instance()->Log(ERROR_LOG, L"load CTMemoryPool failed. Error code is %d.\n", dwError);
		return false;
	}
	m_lpCreateMemoryPool = (LPCreateMemoryPool)GetProcAddress(m_hModule, "CreateMemoryPool");
	dwError = GetLastError();
	if (!m_lpCreateMemoryPool)
	{
		CSingleton<CLogWrapper>::Instance()->Log(ERROR_LOG, L"get creatememorypool interface failed. Error code is %d.\n", dwError);
		return false;
	}
	m_lpDestroyMemoryPool= (LPDestroyMemoryPool)GetProcAddress(m_hModule, "DestroyMemoryPool");
	dwError = GetLastError();
	if (!m_lpDestroyMemoryPool)
	{
		CSingleton<CLogWrapper>::Instance()->Log(ERROR_LOG, L"get destroymemorypool interface failed. Error code is %d.\n", dwError);
		return false;
	}
	return true;
}

void CMemoryMag::Destroy()
{
	if (m_hModule)
	{
		FreeLibrary(m_hModule);
		m_hModule = NULL;
		m_lpCreateMemoryPool = NULL;
		m_lpDestroyMemoryPool= NULL;
	}
}

ICTMemoryPool* CMemoryMag::CreateMemoryPool( MemUnitType type )
{
	if (m_lpCreateMemoryPool)
	{
		return (*m_lpCreateMemoryPool)(type);
	}
	else
	{
		return NULL;
	}
}

bool CMemoryMag::DestroyMemoryPool( ICTMemoryPool* pool )
{
	if (m_lpDestroyMemoryPool)
	{
		return (*m_lpDestroyMemoryPool)(pool);
	}
	else
	{
		return false;
	}
}